package com.zl.freight.ui.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.zl.freight.R;
import com.zl.freight.base.BaseActivity;
import com.zl.freight.mode.UserLogMode;
import com.zl.freight.ui.dialog.ListDialog;
import com.zl.freight.utils.API;
import com.zl.freight.utils.SoapCallback;
import com.zl.freight.utils.SoapUtils;
import com.zl.zlibrary.adapter.UniversalAdapter;
import com.zl.zlibrary.adapter.UniversalViewHolder;

import org.json.JSONArray;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author zhanglei
 * @date 18/05/30
 * 查询用户操作记录
 */
public class QueryUserLogActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_date_start)
    TextView tvDateStart;
    @BindView(R.id.tv_date_end)
    TextView tvDateEnd;
    @BindView(R.id.query_listView)
    ListView queryListView;
    @BindView(R.id.query_trl)
    TwinklingRefreshLayout queryTrl;
    @BindView(R.id.tv_choose_type)
    TextView tvChooseType;
    private boolean isStart = true;
    private int page = 1;
    private String userId;
    private String PayName = "";
    private TimePickerView pvTime;

    private List<UserLogMode> mList = new ArrayList<>();
    private UniversalAdapter<UserLogMode> mAdapter;
    private List<String> dataList = new ArrayList<>();
    private ListDialog listDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_user_log);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initData() {
        getData();
        query();
    }

    private void getData() {
        Map<String, String> params = new HashMap<>();
        SoapUtils.PostNoCheck(mActivity, API.QueryLogType, params, new SoapCallback() {
            @Override
            public void onError(String error) {

            }

            @Override
            public void onSuccess(String data) {
                try {
                    JSONArray array = new JSONArray(data);
                    for (int i = 0; i < array.length(); i++) {
                        dataList.add(array.optJSONObject(i).optString("PayName", ""));
                    }
                    listDialog.setData(dataList);
                } catch (Exception e) {

                }
            }
        });
    }

    private void initListener() {
        queryTrl.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                query();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                page++;
                query();
            }
        });

        listDialog.setOnSelectorDataListener(new ListDialog.OnSelectorDataListener() {
            @Override
            public void onSelector(String data, int position) {
                PayName = data;
                page = 1;
                tvChooseType.setText(data);
                query();
            }
        });
    }

    private void initView() {
        tvTitle.setText("操作记录");
//        tvTitleRight.setText("查询");
        userId = getIntent().getStringExtra("userId");
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
        tvDateEnd.setText(time);
        //时间选择器
        //选中事件回调
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
                if (isStart) {
                    tvDateStart.setText(time);
                } else {
                    tvDateEnd.setText(time);
                }
                query();
            }
        }).setType(new boolean[]{true, true, true, false, false, false}).build();

        queryTrl.setHeaderView(new ProgressLayout(mActivity));

        mAdapter = new UniversalAdapter<UserLogMode>(mActivity, mList, R.layout.user_log_item_layout) {
            @Override
            public void convert(UniversalViewHolder holder, int position, UserLogMode userLogMode) {
                holder.setText(R.id.user_log_name, userLogMode.getPayName());
                holder.setText(R.id.user_log_date, userLogMode.getCreateTime());
            }
        };
        queryListView.setAdapter(mAdapter);

        listDialog = new ListDialog(mActivity, "选择类型");
    }

    @OnClick({R.id.iv_back, R.id.tv_date_start, R.id.tv_date_end, R.id.tv_choose_type, R.id.tv_title_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_title_right:
                query();
                break;
            case R.id.tv_date_start:
                isStart = true;
                pvTime.show();
                break;
            case R.id.tv_date_end:
                isStart = false;
                pvTime.show();
                break;
            case R.id.tv_choose_type://选择查询类型
                listDialog.showDialog(view);
                break;
        }
    }

    /**
     * 查询
     */
    private void query() {
        Map<String, String> params = new HashMap<>();
        params.put("UserId", userId);
        params.put("StartTime", tvDateStart.getText().toString());
        params.put("EndTime", tvDateEnd.getText().toString());
        params.put("PayName", PayName);
        params.put("PageIndex", page + "");
        params.put("PageSize", "10");

        SoapUtils.Post(mActivity, API.QueryUserLog, params, new SoapCallback() {
            @Override
            public void onError(String error) {
                Log.e("body", "");
            }

            @Override
            public void onSuccess(String data) {
                try {
                    if (page == 1) {
                        queryTrl.finishRefreshing();
                        mList.clear();
                    } else {
                        queryTrl.finishLoadmore();
                    }
                    JSONArray array = new JSONArray(data);

                    for (int i = 0; i < array.length(); i++) {
                        mList.add(new Gson().fromJson(array.optString(i), UserLogMode.class));
                    }

                    if (mList.size() <= 0) {
                        showToast("暂无查询结果");
                    }
                    mAdapter.notifyDataSetChanged();
                } catch (Exception e) {

                }
                Log.e("body", "");
            }
        });
    }
}
